<?php


namespace app\libs\TongtuSDK;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class TongTuClient
{
    //const APP_KEY = '82b76df24da14895b21ed5efa80d35b8';
    //const APP_SECRECT = '096ab7aa62af4b308098c4ada5fb24435382508794c849cdb6f67517793c9b9d';
    const APP_KEY = '4d7a3f7d148b442a90660bec6a1e61d8';
    const APP_SECRECT = '6834c7ea9fa547fb83e5173732b5db0671360835e88b4e62acc9ff832aae456c';
    const BASE_URL = 'https://open.tongtool.com';

    const TOKEN = 'ee69843b5c641b0280d0499d179b3c07';
    //const TOKEN = '36780dd67049006cf6d86dff0bbeccf0';
    const MERCHANT_ID =  'e0df079a2329ea1073dd6f6592e2665b';
    const URL_PREFIX = '/api-service';
    public static $white_url = [
        '/open-platform-service/devApp/appToken',
        '/open-platform-service/partnerOpenInfo/getAppBuyerList'
    ];
    public static $app;
    public static $timestamp;
    public static $merchantID;
    public function __construct()
    {
        self::$timestamp = time();
    }

    /**
     * GET请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function get($url, $options = [])
    {
        return self::sendRequest($url, 'GET', $options);
    }

    /** POST请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function post($url, $options = [], $is_json = 1)
    {
        if ($options['query']) {
            if ($is_json) {
                $options['json'] = $options['query'];
            } else {
                $options['form_params'] = $options['query'];
            }

            unset($options['query']);
        }
        return self::sendRequest($url, 'POST', $options);
    }

    /**
     * PUT请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function put($url, $options = [])
    {
        return self::sendRequest($url, 'PUT', $options);
    }

    /**
     * Delete请求
     * @param $url
     * @param array $options
     * @return mixed
     */
    public static function delete($url, $options = [])
    {
        return self::delete($url, $options);
    }

    public static function getOptions($params)
    {
        $baseOptions = [
            'connect_timeout' => 10,
            'timeout' => 10,
            'verify' => false,
            'debug' => false,
            'headers' => [
                'Content-Type'     => 'application/json',
                'api_version'      => '3.0'
            ]
        ];
        $options = array_merge($baseOptions, $params);
        return $options;
    }

    /**
     * 发起HTTP请求
     * @param $url
     * @param string $method
     * @param array $options
     * @return mixed|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function sendRequest($url, string $method, array $options = [])
    {
        $options = self::getOptions($options);
        $client = new Client(['base_uri'=>self::BASE_URL]);
        if(!in_array($url,self::$white_url)) {
            $url = self::URL_PREFIX . $url;
            $url = sprintf('%s?app_token=%s&timestamp=%s&sign=%s',$url,self::TOKEN,self::$timestamp,self::caculateSign());
        }
        $log = [
            'url'=>self::BASE_URL . $url,
            'method' =>$method,
            'params' => $options,
             'response'=>[],
            'error' =>[],
        ];


        try {
            $request = $client->request($method, $url, $options);
            $body = $request->getBody();
            $contents = $body->getContents();
            $response = json_decode($contents, true);
            if(isset($response['message']) && !empty($response['message']) && is_null($response['datas'])){
                throw new \Exception($response['message'],$response['code']);
            }
            $log['response'] = $response;
            tplog($url,$log,'tongtu');
            return $response;
        } catch (ClientException $e) {

            $log['error'] = [
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
            ];
           tplog($url,$log,'tongtu');
            throw new \Exception($e->getMessage(),$e->getCode());
        }

    }


    //计算签名
    public static function caculateSign()
    {
        $signStr = sprintf('app_token%stimestamp%s%s',self::TOKEN,self::$timestamp,self::APP_SECRECT);
        return md5($signStr);
    }




}
